package com.dd.ent.car.common.player;

import android.text.TextUtils;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类：判断是否空白字符串，字符串十六进制工具等
 * <p/>
 * Created by lixianpeng on 2016/3/29.
 * Copyright (c) 2016 Xunlei. All rights reserved.
 *
 * @author lixianpeng
 * @since 1.0
 */
public abstract class StringUtil {

    /**
     * 字符串是否为空
     */
    static public boolean isEmpty(String string) {
        return TextUtils.isEmpty(string);
    }

    /**
     * 字符串是否为空或空白字符串(只包含空格，TAB，回车换行符)
     */
    static public boolean isEmptyOrWhitespace(String string) {
        return isEmpty(string) || string.matches("[\\s\t\r\n]*");
    }

    /**
     * 转为String类型,自动判断字符编码(UTF-8 > GBK > ISO-8859-1)
     * @param data 字节数据
     * @return String类型
     */
    public static String getAppropriateCharsetString(byte[] data) {
        String text = null;
        try {
            CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
            CharBuffer buffer = decoder.decode(ByteBuffer.wrap(data, 2, data.length - 4));
            if (buffer != null) {
                text = buffer.toString();
            }
        } catch (CharacterCodingException e) {
            text = null;
        } finally {
            if (text == null) {
                try {
                    CharsetDecoder decoder = Charset.forName("GBK").newDecoder();
                    CharBuffer buffer = decoder.decode(ByteBuffer.wrap(data, 2, data.length - 4));
                    if (buffer != null) {
                        text = buffer.toString();
                    }
                }catch (CharacterCodingException e) {
                    text = null;
                }finally {
                    if (text == null) {
                        text = new String(data, 2, data.length - 4, Charset.forName("ISO-8859-1"));
                    }
                }
            }
        }
        text = text.trim();
        return text;
    }

    private static final int ONE_SEC_MILLS = 1000;
    private static final int ONE_MIN_MILLS = 1*60*1000;
    private static final int ONE_HOUR_MILLS = 60*ONE_MIN_MILLS;
    private static final int ONE_DAY_MILLS = 24*ONE_HOUR_MILLS;
    private static final int TWO_DAY_MILLS = 2*ONE_DAY_MILLS;


    /**
     * 获取给定时间戳相对于当前时间的相对表示字符串
     * @param timeStamp 要转换的时间戳
     * @return
     */
    public static CharSequence formatRelativeTime(long timeStamp){
        long currentTime = System.currentTimeMillis();
        long distance = currentTime - timeStamp;
        CharSequence formatTime = "";
        if(distance <= ONE_SEC_MILLS){//1 秒前
            formatTime = "1秒前";
        }else if(distance < ONE_MIN_MILLS){
            formatTime = distance/1000 +"秒前";
        }else if(distance < ONE_HOUR_MILLS){
            formatTime = distance/ONE_MIN_MILLS +"分钟前";
        }else if(distance < ONE_DAY_MILLS){
            formatTime = distance/ONE_HOUR_MILLS +"小时前";
        }else if(distance < TWO_DAY_MILLS){
            formatTime = distance/ONE_DAY_MILLS +"天前";
        }else{
            formatTime =
                    android.text.format.DateFormat.format("MM月dd日",timeStamp);
        }

        return formatTime;

    }

    /**
     * 将时长格式化为"HH:mm:ss"或"mm:ss"格式的字符串
     *
     * @param milliseconds 时长毫秒
     * @return 时长式化字符串
     */
    public static String formatDuration(long milliseconds) {
        return formatDuration(milliseconds >= ONE_HOUR_MILLS ? "HH:mm:ss" : "mm:ss", milliseconds);
    }

    /**
     * 将时长格式化为"HH:mm:ss"或"mm:ss"格式的字符串
     *
     * @param format       格式, "HH:mm:ss"或"mm:ss"
     * @param milliseconds 时长毫秒
     * @return 时长式化字符串
     */
    public static String formatDuration(String format, long milliseconds) {
        if (TextUtils.isEmpty(format)) {
            throw new InvalidParameterException("Null or empty format string");
        }
        long seconds = Math.max(0, (milliseconds + 500) / 1000);

        boolean hasHour = false;
        boolean hasMinute = false;
        boolean hasSecond = false;

        String hh = "";
        if (format.contains("HH")) {
            hh = "HH";
            hasHour = true;
        } else if (format.contains("H")) {
            hh = "H";
            hasHour = true;
        }

        String mm = "";
        if (format.contains("mm")) {
            mm = "mm";
            hasMinute = true;
        } else if (format.contains("m")) {
            mm = "m";
            hasMinute = true;
        }

        String ss = "";
        if (format.contains("ss")) {
            ss = "ss";
            hasSecond = true;
        } else if (format.contains("s")) {
            ss = "s";
            hasSecond = true;
        }

        if (!hasHour && !hasMinute && !hasSecond) {
            throw new IllegalArgumentException("Illegal format string");
        }

        long second = seconds % 60;
        long minute = seconds / 60;
        long hour = 0;

        if (hasHour) {
            hour = minute / 60;
            minute = minute % 60;
        }

        StringBuilder stringBuffer = new StringBuilder(format);

        int index = -1;

        if (hasSecond) {
            index = stringBuffer.indexOf(ss);
            if (index != -1) {
                String value = String.valueOf(second);
                if (second < 10 && ss.length() > 1) {
                    value = "0" + value;
                }
                stringBuffer.replace(index, index + ss.length(), value);
            }
        }

        if (hasMinute) {
            index = stringBuffer.indexOf(mm);
            if (index != -1) {
                String value = String.valueOf(minute);
                if (minute < 10 && mm.length() > 1) {
                    value = "0" + value;
                }
                stringBuffer.replace(index, index + mm.length(), value);
            }
        }

        if (hasHour) {
            index = stringBuffer.indexOf(hh);
            if (index != -1) {
                String value = String.valueOf(hour);
                if (hour < 10 && hh.length() > 1) {
                    value = "0" + value;
                }
                stringBuffer.replace(index, index + hh.length(), value);
            }
        }

        return stringBuffer.toString();
    }

    /**
     * 获取string字符串,所有《》括号中的内容
     *
     * @param str 需要传入的字符串
     * @return 书名号中内容的集合
     */
    public static List<String> getBracketText(String str) {
        if (str == null) return null;

        List<String> list = new ArrayList<>();
        String regex = "《(.+?)》";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        while(m.find()){
            list.add(m.group().substring(1, m.group().length()-1));
        }
        return list;
    }
}
